package com.atguigu.gulimall.order.listener;

import com.atguigu.common.constant.OrderConstant;
import com.atguigu.common.constant.SeckillConstant;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.to.mq.WareStockLockTo;
import com.atguigu.gulimall.order.config.OrderRabbitMQConfig;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.to.OrderReleaseTo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class OrderRabbitMQListener {

    @Autowired
    private OrderService orderService;


    @RabbitListener(queues = OrderRabbitMQConfig.ORDER_RELEASE_QUEUE_NAME)
    public void handleOrderCancel(OrderReleaseTo orderReleaseTo, Message message, Channel channel) throws IOException {
        try {
            orderService.cancelOrder(orderReleaseTo.getOrderSn());
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("订单解锁服务正常完成，订单号为 {}", orderReleaseTo.getOrderSn());
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            log.info("订单解锁服务异常，订单号为 {}", orderReleaseTo.getOrderSn());
            throw new RuntimeException(e);
        }
    }

    @RabbitListener(queues = SeckillConstant.SECKILL_ORDER_QUEUE_NAME)
    public void handleSeckillOrder(SeckillOrderTo seckillOrderTo, Message message, Channel channel) throws IOException {
        try {
            orderService.handleSeckillOrder(seckillOrderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("处理秒杀订单正常完成，订单号为 {}", seckillOrderTo.getOrderSn());
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            log.info("处理秒杀订单服务异常，订单号为 {}", seckillOrderTo.getOrderSn());
            throw new RuntimeException(e);
        }
    }
}
